<template>
  <div class="service-request">
    <div class="service-header">
      <h2>安装保修服务</h2>
      <p>专业团队为您提供设备安装、维修和保养服务</p>
    </div>

    <!-- 服务类型选择 -->
    <div class="service-types">
      <h3>选择服务类型</h3>
      <el-row :gutter="20">
        <el-col :span="6" v-for="serviceType in serviceTypes" :key="serviceType.id">
          <div 
            class="service-card"
            :class="{ 'active': selectedServiceType === serviceType.id }"
            @click="selectServiceType(serviceType.id)"
          >
            <div class="service-icon" :style="{ color: serviceType.color }">
              <el-icon :size="36">
                <component :is="serviceType.icon" />
              </el-icon>
            </div>
            <h4>{{ serviceType.name }}</h4>
            <p>{{ serviceType.description }}</p>
            <div class="service-price">¥{{ serviceType.price }}</div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 服务申请表单 -->
    <div class="service-form" v-if="selectedServiceType">
      <h3>服务申请信息</h3>
      <el-form 
        :model="serviceForm" 
        :rules="formRules" 
        ref="serviceFormRef"
        label-width="120px"
        class="request-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactName">
              <el-input v-model="serviceForm.contactName" placeholder="请输入联系人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="serviceForm.contactPhone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="服务地址" prop="serviceAddress">
              <el-input v-model="serviceForm.serviceAddress" placeholder="请输入详细地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预约时间" prop="appointmentTime">
              <el-date-picker
                v-model="serviceForm.appointmentTime"
                type="datetime"
                placeholder="选择预约时间"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm"
                :disabled-date="disabledDate"
                :disabled-hours="disabledHours"
                :disabled-minutes="disabledMinutes"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="设备信息" prop="deviceInfo">
          <el-input 
            v-model="serviceForm.deviceInfo" 
            type="textarea" 
            :rows="3"
            placeholder="请描述需要服务的设备信息（型号、数量、问题描述等）"
          />
        </el-form-item>

        <el-form-item label="问题描述" prop="problemDescription">
          <el-input 
            v-model="serviceForm.problemDescription" 
            type="textarea" 
            :rows="4"
            placeholder="请详细描述遇到的问题或需要安装的内容"
          />
        </el-form-item>

        <el-form-item label="紧急程度" prop="urgency">
          <el-radio-group v-model="serviceForm.urgency">
            <el-radio label="low">一般</el-radio>
            <el-radio label="medium">紧急</el-radio>
            <el-radio label="high">非常紧急</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitServiceRequest" :loading="submitting">
            提交申请
          </el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 服务历史 -->
    <div class="service-history">
      <div class="history-header">
        <h3>服务记录</h3>
        <el-button 
          type="primary" 
          size="small" 
          @click="loadServiceHistory"
          :loading="loadingHistory"
        >
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
      <el-table :data="serviceHistory" style="width: 100%" v-loading="loadingHistory">
        <el-table-column prop="id" label="工单号" width="120" />
        <el-table-column prop="serviceType" label="服务类型" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status) || 'info'">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="appointmentTime" label="预约时间" width="180" />
        <el-table-column prop="contactName" label="联系人" width="100" />
        <el-table-column prop="createTime" label="申请时间" width="180" />
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button size="small" @click="viewServiceDetail(scope.row)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 服务详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="服务详情"
      width="600px"
    >
      <div v-if="selectedService" class="service-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="工单号">{{ selectedService.id }}</el-descriptions-item>
          <el-descriptions-item label="服务类型">{{ selectedService.serviceType }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(selectedService.status) || 'info'">
              {{ getStatusText(selectedService.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="紧急程度">{{ getUrgencyText(selectedService.urgency) }}</el-descriptions-item>
          <el-descriptions-item label="联系人">{{ selectedService.contactName }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ selectedService.contactPhone }}</el-descriptions-item>
          <el-descriptions-item label="服务地址" :span="2">{{ selectedService.serviceAddress }}</el-descriptions-item>
          <el-descriptions-item label="预约时间">{{ selectedService.appointmentTime }}</el-descriptions-item>
          <el-descriptions-item label="申请时间">{{ selectedService.createTime }}</el-descriptions-item>
          <el-descriptions-item label="完成人" v-if="selectedService.completedBy">{{ selectedService.completedBy }}</el-descriptions-item>
          <el-descriptions-item label="完成时间" v-if="selectedService.completedAt">{{ selectedService.completedAt }}</el-descriptions-item>
          <el-descriptions-item label="设备信息" :span="2">{{ selectedService.deviceInfo }}</el-descriptions-item>
          <el-descriptions-item label="问题描述" :span="2">{{ selectedService.problemDescription }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2" v-if="selectedService.remark">{{ selectedService.remark }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, watch } from 'vue'
import { 
  Tools, 
  Setting, 
  Monitor, 
  Wrench,
  Calendar,
  Phone,
  Location,
  User,
  Download,
  Refresh,
  ChatDotRound,
  MagicStick
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '../store/authStore.js'
import { serviceRequestAPI } from '../services/api.js'

export default {
  name: 'ServiceRequest',
  components: {
    Tools,
    Setting,
    Monitor,
    Wrench,
    Calendar,
    Phone,
    Location,
    User,
    Download,
    Refresh,
    ChatDotRound,
    MagicStick
  },
  setup() {
    const serviceFormRef = ref()
    const selectedServiceType = ref('')
    const submitting = ref(false)
    const detailDialogVisible = ref(false)
    const selectedService = ref(null)
    
    // 获取用户认证状态
    const authStore = useAuthStore()

    // 服务类型
    const serviceTypes = [
      {
        id: 'installation',
        name: '设备安装',
        description: '专业安装团队上门安装',
        price: '200',
        icon: 'Download',
        color: '#67C23A'
      },
      {
        id: 'repair',
        name: '设备维修',
        description: '故障诊断与维修服务',
        price: '150',
        icon: 'Tools',
        color: '#E6A23C'
      },
      {
        id: 'maintenance',
        name: '设备保养',
        description: '定期维护保养服务',
        price: '100',
        icon: 'Setting',
        color: '#409EFF'
      },
      {
        id: 'consultation',
        name: '技术咨询',
        description: '专业技术咨询服务',
        price: '50',
        icon: 'ChatDotRound',
        color: '#F56C6C'
      }
    ]

    // 表单数据
    const serviceForm = reactive({
      contactName: '',
      contactPhone: '',
      serviceAddress: '',
      appointmentTime: '',
      deviceInfo: '',
      problemDescription: '',
      urgency: 'low'
    })

    // 表单验证规则
    const formRules = {
      contactName: [
        { required: true, message: '请输入联系人姓名', trigger: 'blur' }
      ],
      contactPhone: [
        { required: true, message: '请输入联系电话', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
      ],
      serviceAddress: [
        { required: true, message: '请输入服务地址', trigger: 'blur' }
      ],
      appointmentTime: [
        { required: true, message: '请选择预约时间', trigger: 'change' }
      ],
      deviceInfo: [
        { required: true, message: '请输入设备信息', trigger: 'blur' }
      ],
      problemDescription: [
        { required: true, message: '请输入问题描述', trigger: 'blur' }
      ]
    }

    // 服务历史数据
    const serviceHistory = ref([])
    const loadingHistory = ref(false)


    // 获取服务历史记录
    const loadServiceHistory = async () => {
      loadingHistory.value = true
      try {
        // 如果用户已登录，从后端获取服务记录
        if (authStore.user.value?.id) {
          const response = await serviceRequestAPI.getUserServiceRequests(authStore.user.value.id)
          const backendHistory = Array.isArray(response) ? response : (response.content || response)
          
          // 转换后端数据格式为前端显示格式
          serviceHistory.value = backendHistory.map(item => ({
            id: item.id,
            serviceType: item.serviceType || '设备维修',
            status: item.status === 'PENDING' ? 'pending' : 
                   item.status === 'IN_PROGRESS' ? 'processing' : 
                   item.status === 'COMPLETED' ? 'completed' : 'pending',
            appointmentTime: item.appointmentTime,
            contactName: item.contactPerson,
            createTime: item.createdAt ? new Date(item.createdAt).toLocaleString('zh-CN') : new Date().toLocaleString('zh-CN'),
            urgency: item.urgencyLevel === 'GENERAL' ? 'low' : 
                    item.urgencyLevel === 'URGENT' ? 'medium' : 'high',
            contactPhone: item.contactPhone,
            serviceAddress: item.serviceAddress,
            deviceInfo: item.deviceInfo,
            problemDescription: item.problemDescription,
            completedBy: item.completedBy,
            completedAt: item.completedAt ? new Date(item.completedAt).toLocaleString('zh-CN') : null
          }))
          
          console.log('从后端加载服务历史记录:', serviceHistory.value.length, '条记录')
        } else {
          // 未登录用户，显示空记录
          serviceHistory.value = []
        }
        
        console.log('服务历史记录加载完成:', serviceHistory.value.length, '条记录 (用户:', authStore.user.value?.username || 'guest', ')')
      } catch (error) {
        console.error('加载服务历史失败:', error)
        ElMessage.error('加载服务记录失败')
        serviceHistory.value = []
      } finally {
        loadingHistory.value = false
      }
    }


    // 选择服务类型
    const selectServiceType = (typeId) => {
      selectedServiceType.value = typeId
    }

    // 禁用日期（只能选择未来7天内的日期）
    const disabledDate = (time) => {
      const today = new Date()
      const maxDate = new Date(today.getTime() + 7 * 24 * 60 * 60 * 1000)
      return time.getTime() < today.getTime() || time.getTime() > maxDate.getTime()
    }

    // 禁用小时（工作时间 8:00-18:00）
    const disabledHours = () => {
      const hours = []
      for (let i = 0; i < 8; i++) {
        hours.push(i)
      }
      for (let i = 19; i < 24; i++) {
        hours.push(i)
      }
      return hours
    }

    // 禁用分钟（允许选择所有分钟）
    const disabledMinutes = () => {
      return []
    }

    // 提交服务申请
    const submitServiceRequest = async () => {
      if (!serviceFormRef.value) return

      await serviceFormRef.value.validate(async (valid) => {
        if (valid) {
          submitting.value = true
          try {
            // 映射紧急程度到后端格式
            const urgencyMapping = {
              'low': 'GENERAL',
              'medium': 'URGENT', 
              'high': 'VERY_URGENT'
            }

            // 准备提交到后端的数据
            const serviceData = {
              userId: authStore.user.value?.id,
              contactPerson: serviceForm.contactName,
              contactPhone: serviceForm.contactPhone,
              serviceAddress: serviceForm.serviceAddress,
              appointmentTime: serviceForm.appointmentTime,
              deviceInfo: serviceForm.deviceInfo,
              problemDescription: serviceForm.problemDescription,
              urgencyLevel: urgencyMapping[serviceForm.urgency] || 'GENERAL'
            }

            console.log('准备提交的服务申请数据:', serviceData)

            // 调用后端接口提交服务申请
            const response = await serviceRequestAPI.createServiceRequest(serviceData)
            
            // 获取工单号
            const serviceId = response.id || 'SR' + new Date().getFullYear() + 
                             String(new Date().getMonth() + 1).padStart(2, '0') + 
                             String(new Date().getDate()).padStart(2, '0') + 
                             String(Math.floor(Math.random() * 1000)).padStart(3, '0')

            ElMessage.success('服务申请提交成功！工单号：' + serviceId)
            resetForm()
            
            // 重新加载服务历史记录
            await loadServiceHistory()
          } catch (error) {
            console.error('服务申请提交失败:', error)
            ElMessage.error('提交失败：' + (error.message || '网络错误，请稍后重试'))
          } finally {
            submitting.value = false
          }
        }
      })
    }

    // 重置表单
    const resetForm = () => {
      if (serviceFormRef.value) {
        serviceFormRef.value.resetFields()
      }
      selectedServiceType.value = ''
    }

    // 查看服务详情
    const viewServiceDetail = (service) => {
      selectedService.value = service
      detailDialogVisible.value = true
    }

    // 获取状态类型
    const getStatusType = (status) => {
      const typeMap = {
        'pending': 'warning',
        'in_progress': 'primary',
        'completed': 'success',
        'cancelled': 'danger'
      }
      return typeMap[status] || 'info'
    }

    // 获取状态文本
    const getStatusText = (status) => {
      const textMap = {
        'pending': '待处理',
        'in_progress': '进行中',
        'completed': '已完成',
        'cancelled': '已取消'
      }
      return textMap[status] || '未知'
    }

    // 获取紧急程度文本
    const getUrgencyText = (urgency) => {
      const textMap = {
        'low': '一般',
        'medium': '紧急',
        'high': '非常紧急'
      }
      return textMap[urgency] || '一般'
    }

    // 监听用户状态变化，当用户切换时重新加载服务记录
    watch(() => authStore.user.value?.id, (newUserId, oldUserId) => {
      if (newUserId !== oldUserId) {
        console.log('检测到用户切换，重新加载服务记录和用户信息')
        loadServiceHistory()
        loadUserInfo()
      }
    }, { immediate: false })

    // 加载用户信息并填充联系电话
    const loadUserInfo = () => {
      if (authStore.user.value?.phone) {
        serviceForm.contactPhone = authStore.user.value.phone
      }
    }

    // 组件挂载时加载服务历史和用户信息
    onMounted(() => {
      loadServiceHistory()
      loadUserInfo()
    })

    return {
      serviceFormRef,
      selectedServiceType,
      submitting,
      detailDialogVisible,
      selectedService,
      serviceTypes,
      serviceForm,
      formRules,
      serviceHistory,
      selectServiceType,
      disabledDate,
      disabledHours,
      disabledMinutes,
      submitServiceRequest,
      resetForm,
      viewServiceDetail,
      getStatusType,
      getStatusText,
      getUrgencyText,
      loadServiceHistory,
      loadingHistory
    }
  }
}
</script>

<style scoped>
.service-request {
  padding: 20px;
}

.service-header {
  margin-bottom: 30px;
  text-align: center;
}

.service-header h2 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 28px;
  font-weight: 600;
}

.service-header p {
  margin: 0;
  color: #666;
  font-size: 16px;
}

.service-types {
  margin-bottom: 30px;
}

.service-types h3 {
  margin: 0 0 20px 0;
  color: #333;
  font-size: 20px;
}

.service-card {
  background: #fff;
  border: 2px solid #e4e7ed;
  border-radius: 16px;
  padding: 25px 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  height: 220px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  position: relative;
  overflow: hidden;
}


.service-card:hover {
  border-color: #409eff;
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(64, 158, 255, 0.2);
}

.service-card.active {
  border-color: #409eff;
  background: linear-gradient(135deg, #f0f8ff 0%, #e6f3ff 100%);
  box-shadow: 0 8px 25px rgba(64, 158, 255, 0.15);
}


.service-icon {
  margin-bottom: 15px;
  transition: all 0.3s ease;
}

.service-card:hover .service-icon {
  transform: scale(1.1);
}

.service-card h4 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.service-card p {
  margin: 0 0 15px 0;
  color: #666;
  font-size: 14px;
  flex-grow: 1;
}

.service-price {
  color: #f56c6c;
  font-size: 18px;
  font-weight: 600;
}

.service-form {
  margin-bottom: 30px;
}

.service-form h3 {
  margin: 0 0 20px 0;
  color: #333;
  font-size: 20px;
}

.request-form {
  background: #fff;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.history-header h3 {
  margin: 0;
  color: #333;
  font-size: 20px;
}

.service-detail {
  padding: 20px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .service-request {
    padding: 15px;
  }
  
  .service-card {
    height: auto;
    min-height: 180px;
  }
  
  .request-form {
    padding: 20px;
  }
}
</style>
